package cn.tedu.carehome.foundation.security;

import cn.tedu.carehome.foundation.mapper.StaffMapper;
import cn.tedu.carehome.foundation.pojo.vo.StaffLoginInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * Spring Security处理认证时使用到的获取员工登录详情的实现类
 *
 * @author 张子豪
 * @version 0.0.1
 */
@Service
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private StaffMapper StaffMapper;


    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        //使用参数s作为参数，调用AdminMapper的getLoginInfoByUsername执行查询
        log.debug("String:{}",s);
       StaffLoginInfoVo staffLoginInfoVo = StaffMapper.getLoginInfoByUsername(s);
       log.debug("参数:{}",staffLoginInfoVo);
        //判断查询结果是否为NULL
        if (staffLoginInfoVo == null) {
            //是：返回null
            return null;
        }
        List<String> permissions=staffLoginInfoVo.getPermissions();
        List<SimpleGrantedAuthority> authorities = new ArrayList<>();
        for(String permission:permissions) {
            SimpleGrantedAuthority authority = new SimpleGrantedAuthority(permission);
            authorities.add(authority);
        }
       StaffDetails staffDetails = new StaffDetails(
               staffLoginInfoVo.getId(),
               staffLoginInfoVo.getUsername(),
               staffLoginInfoVo.getPassword(),
               staffLoginInfoVo.getEnable() == 1,
                authorities
        );
        log.debug("即将向Spring Security返回UserDetails对象：{}", staffDetails);
        return staffDetails;
    }
}
